import { reactive, ref, computed, onMounted } from 'vue';
import _ from "lodash";
import Bus from '@/utils/bus';
import { useRoute, useRouter } from 'vue-router';
import * as Store from "@/store";
import * as Utils from '../utils/utils';
import useUtils from './useUtils';
// import useContent from './useContent';
import { Message } from '@arco-design/web-vue';
import * as StaticData from '../data/toolBarData';
import * as Api from '@/api/filmRead/filmRead';
import { saveYaYData, submitDataOver, getTrace } from '@/api/readPathology/readPathology';
import type * as FilmReadType from '@/api/filmRead/filmRead.d';
import type { CallBackData } from '@/components/dialog/type.d';
import {actionLesionList, lesionList, merList} from "../data/toolBarData";
// 定义初始属性
const headerHooksData = reactive({
  queryVisibile: true,
  markVisibile: true,
  currentIndex: 0,
  selectedCtWindow: "",
  opacity: 50,
  brushRadius: 10,
  brushLayer: 1,
  eraserRadius: 10,
  eraserLayer: 1,
  sideLength: 20,
  queryBarList: _.cloneDeep(StaticData.queryBarList),
  markBarList: _.cloneDeep(StaticData.markBarList),
  radioVisible: false,
  radioChecked: undefined as unknown as boolean,
  markScrapVisible: false,
  scrapValue: '',
  discardRemark: '',
  submitVisible: false,
  sectionVisible: false
});
// const formRef = ref();
const formRefVal = ref();
const toolBarItem = ref<any>({});
const currentLesion = ref<FilmReadType.LesionItem>({} as FilmReadType.LesionItem);
const useHeader = (type: string) => {
  const FilmRead = Store.useFilmRead();
  const interfaceData = FilmRead.interfaceData;
  const dictionaryData = FilmRead.dictionaryData;
  const getResultData = FilmRead.getResultData;
  const route = useRoute();
  const router = useRouter();
  const toolList = dictionaryData.toolList;
  const lesionList = dictionaryData.lesionList;
  const seriesList = interfaceData.seriesList;
  const UtilsHooks = useUtils();
  // const ContentHooks = useContent();
  // 处理基础窗宽窗位值
  if (interfaceData.pageSettingList.defaultWindow) {
    headerHooksData.selectedCtWindow = interfaceData.pageSettingList.defaultWindow;
  }
  // 通过计算属性处理查看工具栏
  const queryBarList = computed(() => {
    let tempArr = headerHooksData.queryBarList.filter(
      (item) => item.type === type || item.type.includes(type)
    );
    // 针对超声视频追踪算法按钮控制的逻辑，配置+查看模式
    if(!FilmRead.interfaceData.pageSettingList.needVideoTrace || route.query.type === 'query'){
      tempArr = tempArr.filter(item => item.code !== 'trace')
    }
    return reactive(tempArr);
  })
  // 通过计算属性处理标注工具栏
  const markBarList = computed(() => {
    let tempArr = headerHooksData.markBarList.filter((item) =>
      Object.keys(toolList).includes(item.toolType)
    );
    tempArr.length !== 0 &&
      (tempArr = tempArr.map((item) => {
        return {
          ...item,
          isSecondVisible: false,
          lesionValue: "",
        };
      }));
    return reactive(tempArr);
  });
  // 得到全部工具栏
  const allBarList = computed(() => queryBarList.value.concat(markBarList.value));
  /**
   * 禁用浏览器右键菜单
   * @returns false
   */
  const handleRightMenu = (dom: any, flag = false) => {
    dom.oncontextmenu = () => {
      return flag;
    };
  }
  /**
   * 顶部返回按键事件
   */
  const handlePageBack = () => {
    router.back();
  }
  /**
   * 页面顶部工具标题切换显示隐藏事件
   * @param type 当前标题点击的类型 query为查看工具点击 mark为标注工具点击
   */
  const handleBarTitleClick = (type: string) => {
    if (type === 'query') {
      headerHooksData.markVisibile = true;
      headerHooksData.queryVisibile = !headerHooksData.queryVisibile;
    } else {
      headerHooksData.queryVisibile = true;
      headerHooksData.markVisibile = !headerHooksData.markVisibile;
    }
    queryBarList.value.map(item => item.isVisible = false);
    markBarList.value.map(item => item.isVisible = false);
  }

  /**
   * 工具栏点击事件
   * @param item 当前点击的每一项
   * @param ctWlww 调窗值
   */
  const handleToolBarClick = (item: Header.QueryDataList | Header.MarkDataList, it?: FilmReadType.LesionItem, toolClickType?: boolean) => {
    toolBarItem.value = {
      currentItem: item
    }
    //当前工具
    headerHooksData.currentIndex = item.id
    if(!toolClickType && item.isActive){//反选
      item.isActive = false
      item.isVisible = false
      headerHooksData.currentIndex = 2;//恢复默认
      (item as Header.MarkDataList).lesionValue = ''//恢复
    }else if(!toolClickType && !item.isActive){//选中
      item.isActive = true
      item.isVisible = true
      headerHooksData.currentIndex = item.id;
    }
    if(toolClickType && StaticData.lesionList.includes(item.code)){
      item.isActive = true
      item.isVisible = false
    }else if(toolClickType && StaticData.actionLesionList.includes(item.code)){
      item.isActive = true
      item.isVisible = true
    }

    // 做左键互斥逻辑
    if(StaticData.merList.includes(item.code) && item.isActive && !toolClickType){
      // 得到左键互斥集合
      const merObjList = allBarList.value.filter(it => StaticData.merList.includes(it.code));
      Utils.makeListMer(merObjList, item);
    }
    // 重置类按钮触发逻辑 和算法追踪触发逻辑
    StaticData.resetList.includes(item.code) && (item.isActive = false);
    // 自由画笔和橡皮擦
    if (_.cloneDeep(StaticData.burshList).includes(item.code)) {
      const radius = (item.code === 'FREEHAND_DAUBER'? headerHooksData.brushRadius : headerHooksData.eraserRadius);
      const layers = (item.code === 'FREEHAND_DAUBER'? headerHooksData.brushLayer : headerHooksData.eraserLayer);
      toolBarItem.value.radius = radius;
      toolBarItem.value.layers = layers;
    }
    // 标注工具
    if (Object.keys(item).includes('toolType')) {
      it && (currentLesion.value = it);
      toolBarItem.value.lesion = currentLesion.value;
    }
    toolBarItem.value.isTool = Boolean(toolClickType);

    Bus.emit("toolBarClick", toolBarItem.value);
  }

  /**
   * 调窗下拉改变事件
   * @param value 当前下拉选择值
   * @param item 当前工具栏的一项
   */
  const handleChangeWindow = (value: string, item: Header.QueryDataList) => {
    headerHooksData.selectedCtWindow = value;
    toolBarItem.value = {
      currentItem: item,
      ctWlww: headerHooksData.selectedCtWindow
    }
    Bus.emit("toolBarClick", toolBarItem.value);
  }

  /**
   * 工具触发器的滑块的事件
   * @param item 当前点击的工具栏的每一项
   * @param type 当前的工具类型
   * @param value 当前操作的数据的值
   */
  const handleSliderChange = (item: Header.QueryDataList | Header.MarkDataList, type: string = '', value: number | [number, number]) => {
    headerHooksData.currentIndex = item.id;
    toolBarItem.value = {
      currentItem: item,
      toolType: type,
      lesion: currentLesion.value
    }
    // 透明度
    if (['transparency'].includes(item.code)) {
      headerHooksData.opacity = Math.round(headerHooksData.opacity)
      toolBarItem.value.value = headerHooksData.opacity;
    }
    // 自由画笔
    if (_.cloneDeep(StaticData.burshList).includes(item.code)) {
      headerHooksData.brushRadius = Math.round(headerHooksData.brushRadius)
      headerHooksData.eraserRadius = Math.round(headerHooksData.eraserRadius)
      headerHooksData.brushLayer = Math.round(headerHooksData.brushLayer)
      headerHooksData.eraserLayer = Math.round(headerHooksData.eraserLayer)
      const radius = (type === 'brushRadius'? headerHooksData.brushRadius : headerHooksData.eraserRadius);
      const layers = (type === 'brushLayer'? headerHooksData.brushLayer : headerHooksData.eraserLayer);
      toolBarItem.value.radius = radius;
      toolBarItem.value.layers = layers;
    }
    Bus.emit("toolBarClick", toolBarItem.value);
  }

  /**
   * 标注工具二层触发器的病灶选择函数
   * @param item 当前选择的工具项
   * @param it 当前病灶项
   */
  const handleBrushLesionClick = (item: Header.MarkDataList, it?: FilmReadType.LesionItem) => {
    item.isSecondVisible = !item.isSecondVisible;
    if (it) {
      item.lesionValue = FilmRead.dictionaryData.lesionList[it.lesion].name;
    }
    toolBarItem.value = {
      currentItem: item,
      lesion: it,
    }
    // 自由画笔
    if (['FREEHAND_DAUBER'].includes(item.code)) {
      toolBarItem.value.radius = headerHooksData.brushRadius;
      toolBarItem.value.layers = headerHooksData.brushLayer;
    }
    // 长方体
    if (['CUBOID'].includes(item.code)) {
      toolBarItem.value.sideLength = headerHooksData.sideLength;
    }
    Bus.emit("toolBarClick", toolBarItem.value);
  }

  /**
   * 阴阳性选择函数
   * @param type 阴阳性类型
   */
  const handleRadioClick = async (type: number) => {
    if (seriesList.length !== 0) {
      headerHooksData.radioChecked = type === 1;
      const params = {
        arId: seriesList[FilmRead.currentThumbnailIndex].id,
        yay: type,
      };
      const res = await saveYaYData(params);
    }
  }

  /**
   * MPR阅片端的保存按钮事件
   */
  const handleMprSave = () => {
    Bus.emit("toolBarClick", {
      isSave: true
    });
  }

  /**
   * 标记废片按钮点击事件
   */
  const handleMarkDesert = () => {
    headerHooksData.markScrapVisible = true;
  }

  /**
   * 提交按钮点击事件
   */
  const handleSubmit = () => {
    // headerHooksData.submitVisible = true;
    // 否则正常校验阴阳性
    const yayStatus = validateYay();
    // 超声视频追踪算法校验
    if (interfaceData.pageSettingList.imageLayout === "VIDEO_ANNO" && interfaceData.pageSettingList.needVideoTrace) {
      const videoTraceRes = validateVideoTrace();
      if (!videoTraceRes.status) {
        // videoTraceStatus 为true校验通过 否则不通过
        // UtilsHooks.lesionEvent.lesionRemoveActive();
        UtilsHooks.lesionEvent.frameActive(videoTraceRes.id)
        UtilsHooks.seriesEvent.seriesChangeActive();
        return
      }
    }
    if (!yayStatus) {
      // yayStatus为true校验通过 否则需要校验
      Message.error("请选择阴阳性，再提交病理切片！");
      return
    }
    if (yayStatus) {
      // 校验大征象
      const seriesStatus = validateSeriesComp();
      if (!seriesStatus) {
        // seriesStatus 为true校验通过 否则不通过
        UtilsHooks.lesionEvent.lesionRemoveActive();
        UtilsHooks.seriesEvent.seriesChangeActive();
        return
      }
      if (yayStatus && seriesStatus) {
        // 校验小征象
        const imageSeriesCompStatus = validateImageSeriesComp();
        if (!imageSeriesCompStatus.status) {
          // imageSeriesCompStatus 为true校验通过 否则不通过
          imageSeriesCompStatus.lesionId && UtilsHooks.lesionEvent.lesionSetActive(imageSeriesCompStatus.lesionId, true);
          imageSeriesCompStatus.lesionId && UtilsHooks.lesionEvent.contentActive(imageSeriesCompStatus.lesionId);
        }
        if (imageSeriesCompStatus.status) {
          headerHooksData.submitVisible = true;
        }
      }
    }
  }

  /**
   * 上一个按钮点击事件
   */
  const handlePrevClick = () => {
    FilmRead.prevIndex({
      id: route.query.id as unknown as number,
      type: route.query.type as unknown as string,
      dataType: route.query.dataType as unknown as string
    });
  }

  /**
   * 下一个按钮点击事件
   */
  const handleNextClick = () => {
    FilmRead.nextIndex({
      id: route.query.id as unknown as number,
      type: route.query.type as unknown as string,
      dataType: route.query.dataType as unknown as string
    });
  }

  /**
   * 提交废片弹窗确定方法
   * @param data 提交弹窗关闭前参数
   */
  const handleMarkScrapVisible = async (data: CallBackData) => {
    if (data.status === 'save') {
      data.done(true);
      const params = {
        arIdList: [seriesList[FilmRead.currentThumbnailIndex].id],
        status: 3,
        discardCode: headerHooksData.scrapValue,
        discardRemark: headerHooksData.discardRemark
      }
      const res = await submitDataOver(params);
      Message.success('保存成功！');
      // 到下一序列
      // 无序列就关闭页面
      const { id, type } = route.query;
      if(id && type === "create") {
        const seriesList = await Api.getAnnoArList({taskId: +id});
        if (seriesList.data.arList) {
          // setTimeout(() => {
          //   window.opener = null;
          //   window.open(window.location.href, '_self');
          // }, 1000);
          router.go(0);
        } else {
          headerHooksData.sectionVisible = true;
        }
      }
      if (type !== "create") {
        // setTimeout(() => {
        //   window.opener = null;
        //   window.open('', '_self');
        //   window.close();
        // }, 1000);
        router.back();
      }
    } else {
      headerHooksData.scrapValue = '';
      headerHooksData.discardRemark = '';
    }
    headerHooksData.markScrapVisible = data.flag;
  }

  /**
   * 提交弹窗关闭按钮事件
   */
  const handleCancel = () => {
    headerHooksData.submitVisible = false;
  }

  /**
   * 最终保存数据方法
   * @param data 提交弹窗关闭前参数 其中save类型为当前点击并关闭操作 more类型为当前点击并获取新序列操作
   */
  const saveData = async (data: Header.CallBack) => {
    const params = {
      arIdList: [FilmRead.interfaceData.seriesList[FilmRead.currentThumbnailIndex].id],
      status: 2,
    };
    const res = await submitDataOver(params);
    Message.success('保存成功！');
    const { id, type } = route.query as unknown as any;
    if(id && type === "create" && data.status === "more") {
      const seriesList = await Api.getAnnoArList({taskId: +id});
      if (seriesList.data.arList) {
        router.go(0);
      } else {
        headerHooksData.sectionVisible = true;
      }
      headerHooksData.submitVisible = data.flag;
    }
    if (id && (type !== "create" || (data.status === "save" && type === "create"))) {
      // setTimeout(() => {
      //   window.opener = null;
      //   window.open('', '_self');
      //   window.close();
      // }, 1000);
      headerHooksData.submitVisible = data.flag;
      router.back();
    }
  }

  /**
   * 提交弹窗点击事件函数
   * @param data 提交弹窗关闭前参数 其中save类型为当前点击并关闭操作 more类型为当前点击并获取新序列操作
   */
  const handleSubmitVisible = (data: Header.CallBack) => {
    saveData(data);
    // 调用提交接口
    // if (yayStatus && seriesStatus && imageSeriesCompStatus.status) {
    //   saveData(data);
    // }
  }

  /**
   * 校验当前是否为废片
   * @returns 布尔值
   */
  const validateDiscard = () => {
    if (FilmRead.interfaceData.pageSettingList.discardCodeList === "") {
      return true;
    }
    if (FilmRead.interfaceData.pageSettingList.discardCodeList !== "" && headerHooksData.scrapValue !== '') {
      return true;
    }
    return false;
  }

  /**
   * 校验当前是否阴阳性有值
   * @returns 布尔值
   */
  const validateYay = () => {
    if (!FilmRead.interfaceData.pageSettingList.showYay) {
      return true;
    }
    if (FilmRead.interfaceData.pageSettingList.showYay && headerHooksData.radioChecked !== undefined) {
      return true;
    }
    return false;
  }

  /**
   * 校验大征象辅助函数
   * @returns 布尔值
   */
  const validateSeriesComp = () => {
    let status = true;
    const seriesList = FilmRead.dictionaryData.seriesDataList && FilmRead.dictionaryData.seriesDataList[FilmRead.interfaceData.seriesList[FilmRead.currentThumbnailIndex].seriesUid];
    seriesList && seriesList.forEach((item: { required: any; result: string | null; name: string; code: string; }) => {
      if (!status) return;
      if (item.required && (item.result === '' || item.result === null)) {
        // console.log(formRefVal.value, "formRef.value", item);
        // formRefVal.value.setFields({
        //   [item.code]: {
        //     status: "error",
        //     message: `${item.name}不能为空`
        //   }
        // })
        Message.error(`序列征象-${item.name}不可为空！`);
        status = false;
        return status;
      }
    })
    return status;
  }
  const formRef = (el: any) => {
    if (el) {
      // console.log(el, "asdasdasda");
      formRefVal.value = el;
    }
  };

  /**
   * 校验小征象辅助函数
   * @returns 布尔值
   */
  const validateImageSeriesComp = () => {
    let status = true;
    let lesionId = null;
    const imageSeriesList = FilmRead.dictionaryData.imageSeriesDataList && Object.entries(FilmRead.dictionaryData.imageSeriesDataList);
    imageSeriesList && imageSeriesList.forEach((item: any[]) => {
      if (!status) return;
      item[1] && item[1].forEach((it: { required: any; result: string | null; name: any; }) => {
        if (!status) return;
        if (it.required && (it.result === '' || it.result === null)) {
          Message.error(`标注征象-${it.name}不可为空`);
          status = false;
          lesionId = item[0];
          return status;
        }
      })
    })
    return {
      lesionId,
      status
    };
  }

  /**
   * 校验超声视频追踪算法函数
   * @returns 布尔值
   */
  const validateVideoTrace = () => {
    let result = {
      status: true,
      id: null as unknown as number
    }
    // let status = true;
    // 需要校验追送算法
    dictionaryData.frameList && dictionaryData.frameList.forEach((item, index) => {
      if (!result.status) return;
      if (!item.algProcessed) {
        let str = ""
        index < 10 && (str = `帧段-0${index +1}未追踪，请追踪后在进行提交！`);
        index > 10 && (str = `帧段-${index +1}未追踪，请追踪后在进行提交！`);
        Message.error(str);
        result.status = false;
        result.id = item.id;
        return result;
      }
    })
    return result;
  }

  /**
   * 无新切片弹窗关闭前的函数
   * @param data 无新切片弹窗关闭前的参数
   */
  const handleSectionVisible = (data: CallBackData) => {
    if (data.status === 'save') {
      data.done(true);
      headerHooksData.sectionVisible = data.flag;
      // sectionVisible.value = data.flag;
      router.back();
    }
  }

  const getCompStatus = () => {
    headerHooksData.radioVisible = FilmRead.interfaceData.pageSettingList.showYay;
    if (FilmRead.interfaceData.resultDataList.yay) {
      headerHooksData.radioChecked = FilmRead.interfaceData.resultDataList.yay === 1;
    }
  }

  const resetHookData = () => {
    headerHooksData.queryVisibile = true;
    headerHooksData.markVisibile = true;
    headerHooksData.currentIndex = 0;
    headerHooksData.selectedCtWindow = "";
    headerHooksData.opacity = 50;
    headerHooksData.brushRadius = 10;
    headerHooksData.brushLayer = 1;
    headerHooksData.eraserRadius = 10;
    headerHooksData.eraserLayer = 1;
    headerHooksData.sideLength = 20;
    headerHooksData.queryBarList = _.cloneDeep(StaticData.queryBarList);
    headerHooksData.markBarList = _.cloneDeep(StaticData.markBarList);
    headerHooksData.radioVisible = false;
    headerHooksData.radioChecked = undefined as unknown as boolean;
    headerHooksData.markScrapVisible = false;
    headerHooksData.scrapValue = '';
    headerHooksData.discardRemark = '';
    headerHooksData.submitVisible = false;
    headerHooksData.sectionVisible = false;
  }

  onMounted(() => ([getCompStatus()]));

  return {
    headerHooksData,
    toolBarItem,
    queryBarList,
    markBarList,
    formRef,
    handleRightMenu,
    handlePageBack,
    handleBarTitleClick,
    handleToolBarClick,
    handleChangeWindow,
    handleSliderChange,
    handleBrushLesionClick,
    handleRadioClick,
    handleMprSave,
    handleMarkDesert,
    handleSubmit,
    handlePrevClick,
    handleNextClick,
    handleMarkScrapVisible,
    handleCancel,
    handleSubmitVisible,
    handleSectionVisible,
    resetHookData
  }
}
export default useHeader;